package com.laikan.reader.core.adapter;

import android.content.Context;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.laikan.reader.R;
import com.laikan.reader.database.History;

import java.util.List;

/**
 * Created by wx on 16/8/12.
 */
public class ReadHistoryAdapter extends BaseAdapter {

    ViewHolder holder = null;
    List<History> mDatas;
    Context mContext;
    boolean mSelectorShow = false;
    private boolean mSelectAll = false;

    public ReadHistoryAdapter(Context context, List<History> datas) {
        mContext = context;
        mDatas = datas;
    }

    public void updataAll(List<History> datas) {
        mDatas.clear();
        mDatas = datas;
        mSelectorShow = false;
        notifyDataSetChanged();
    }

    public void updataSelector(boolean selectorShow) {
        this.mSelectorShow = selectorShow;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public Object getItem(int i) {
        return mDatas.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        History h = mDatas.get(position);
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = View.inflate(mContext, R.layout.readehistory_item, null);
            holder.book_image = (SimpleDraweeView)convertView.findViewById(R.id.book_image);
            holder.book_name = (TextView)convertView.findViewById(R.id.book_name);
            holder.book_auth = (TextView)convertView.findViewById(R.id.sort_author);
            holder.book_updata = (TextView)convertView.findViewById(R.id.book_updata);
            holder.history_selector = (CheckBox)convertView.findViewById(R.id.history_selector);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.book_image.setImageURI(Uri.parse(h.getBookCover()));
        holder.book_name.setText(h.getBookName());
        holder.book_auth.setText(h.getAuthorName());
        holder.book_updata.setText("上次阅读至: " + h.getLastReadChapter());

        if (mSelectorShow) {
            holder.history_selector.setVisibility(View.VISIBLE);
            if (h.getSelected()){
                holder.history_selector.setChecked(true);
            }else {
                holder.history_selector.setChecked(false);
            }
        }else {
            holder.history_selector.setVisibility(View.GONE);
        }
        return convertView;
    }

    private class ViewHolder {

        SimpleDraweeView book_image;
        TextView book_name, book_auth, book_updata;
        CheckBox history_selector;
    }
}
